import 'package:dio/dio.dart';
import 'package:flutter_app/utils/config.dart';
import 'package:flutter_app/utils/utils.dart';

/// Token拦截器
class TokenInterceptors extends InterceptorsWrapper {
  String _token;

  @override
  onRequest(RequestOptions options) async {
    String token = await LocalStorage.get(Config.TOKEN_KEY);
    if (token != null && token.isNotEmpty) {
      options.headers["Cookie"] = 'X-ADV-TOKEN=$token';
    }
    return options;
  }

  @override
  onResponse(Response response) async {
    try {
      List responseJson = response.headers['set-cookie'];
      _token = responseJson[0].split('; ')[0].split('=')[1];
      if (response.statusCode == 204 && _token != null) {
        await LocalStorage.save(Config.TOKEN_KEY, _token);
      }
    } catch (e) {
      print(e);
    }
    return response;
  }
}
